// pages/homePage/heartRate/heartRate.js
const app = getApp();
import F2 from '@antv/wx-f2';
let chart = null;
F2.Global.setTheme({
  appendPadding: 15
});

function initChart(canvas, width, height) { // 使用 F2 绘制图表
  const data = [{
    heartRate: 0,
    avaHeartRate: 0,
    x: "周一"
  }]
  chart = new F2.Chart({
    el: canvas,
    width: width,
    height: height
  });

  chart.source(data, {
    heartRate: {
      ticks: [0, 20, 40, 60, 80, 100, 120]
    }
  });
  chart.tooltip({
    showItemMarker: false,
    background: {
      radius: 2,
      fill: '#F77775'
    },
    valueStyle: {
      fontSize: 10,
      color: "#FFFFFF"
    },
    onShow(ev) {
      const {
        items
      } = ev;
      items[0].name = null;
      items[0].value = items[0].value + "次";
    }
  });
  let barWidth = 30 * (wx.getSystemInfoSync().windowWidth / 375) / 2;

  chart.interval().position('x*heartRate').color('l(0) 0:#F9A39E 1:#F77775').style({
    radius: [5, 5, 0, 0]
  }).size(barWidth);

  chart.render();
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceNum: "",
    weekDay: '',
    end: "",
    now: "",
    nowWeek: "",
    weekText: "",
    nowMonth: "",
    monthText: "",
    nowYear: "",
    yearText: "",
    curTab: "1",
    maxInt: [2147483647, -2147483648],
    maxRateDay: "0",
    minRateDay: "0",
    avaRateDay: "0",
    maxRateWeek: "0",
    minRateWeek: "0",
    avaRateWeek: "0",
    maxRateMonth: "0",
    minRateMonth: "0",
    avaRateMonth: "0",
    maxRateYear: "0",
    minRateYear: "0",
    avaRateYear: "0",
    opts_day: {
      onInit: initChart
    },
    opts_week: {
      onInit: initChart
    },
    opts_month: {
      onInit: initChart
    },
    opts_year: {
      onInit: initChart
    }
  },
  onReady: function() {
    this.getHeartRateData(this.data.deviceNum, this.data.now, 1);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let now = new Date(new Date().getTime() - 24 * 60 * 60 * 1000).format("yyyy/MM/dd");
    let nowMonth = new Date().format("yyyy/MM");
    let weekday = app.utils.formatWeekday(new Date(now).getDay());
    let startWDate = new Date(now).getTime() - 6 * 24 * 60 * 60 * 1000;
    startWDate = new Date(startWDate).format("yyyy/MM/dd");
    let weekText = startWDate + " - " + now;
    let startMDate = new Date(now).getTime() - 14 * 24 * 60 * 60 * 1000;
    startMDate = new Date(startMDate).format("yyyy/MM/dd");
    let monthText = startMDate + " - " + now;
    let startYDate = new Date(now).getTime() - 335 * 24 * 60 * 60 * 1000;
    startYDate = new Date(startYDate).format("yyyy/MM");
    let yearText = startYDate + " - " + nowMonth;

    this.setData({
      weekDay: weekday,
      now: now,
      nowWeek: now,
      weekText: now,
      nowMonth: now,
      nowYear: now,
      end: now,
      weekText: weekText,
      monthText: monthText,
      yearText: yearText,
      deviceNum: wx.getStorageSync("deviceNum")
    })


  },
  circleCanves(option) {
    var cxt_arc = wx.createCanvasContext(option.id);
    var gr = cxt_arc.createLinearGradient(0, 100, 100);
    gr.addColorStop(0, option.colorStart);
    gr.addColorStop(1, option.colorEnd);
    cxt_arc.setLineWidth(option.ringWidth);
    cxt_arc.setStrokeStyle('#d2d2d2');
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(option.x, option.y, option.radius, Math.PI * option.trackStart, Math.PI * option.trackEnd, false);
    //设置原点(80,80)，半径为50的圆的路径到当前路径
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.setLineWidth(option.ringWidth);
    cxt_arc.strokeStyle = gr;
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(option.x, option.y, option.radius, Math.PI * option.position1, Math.PI * option.position2, false);
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.draw();
  },
  drawCir(el, w) {
    let width = wx.getSystemInfoSync().windowWidth;
    this.circleCanves({
      id: el,
      ringWidth: width / 375 * 5,
      radius: width / 375 * 25,
      position1: 0.5,
      position2: 2 * w + 0.5,
      x: width / 375 * 30,
      y: width / 375 * 30,
      colorStart: "#F9A39E",
      colorEnd: "#F77775",
      trackStart: 2,
      trackEnd: 0
    });
  },
  bindDateChange(e) {

    let weekDay = app.utils.formatWeekday(new Date(e.detail.value).getDay())
    this.setData({
      now: e.detail.value.replace(/-/g, "/"),
      weekDay: weekDay
    })

    this.getHeartRateData(this.data.deviceNum, e.detail.value, 1);
  },
  bindDateChangeWeek(e) {
    let startDate = new Date(e.detail.value).getTime() - 6 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM/dd");
    let weekText = startDate + " - " + e.detail.value.replace(/-/g, "/");

    this.setData({
      nowWeek: e.detail.value,
      weekText: weekText
    })
    this.getHeartRateData(this.data.deviceNum, e.detail.value, 2);
  },
  bindDateChangeMonth(e) {
    let startDate = new Date(e.detail.value).getTime() - 14 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM/dd");
    let monthText = startDate + " - " + e.detail.value.replace(/-/g, "/");

    this.setData({
      nowMonth: e.detail.value,
      monthText: monthText
    })

    this.getHeartRateData(this.data.deviceNum, e.detail.value, 3);
  },
  bindDateChangeYear(e) {
    let startDate = new Date(e.detail.value).getTime() - 335 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM");
    let yearText = startDate + " - " + new Date(e.detail.value).format("yyyy/MM");

    this.setData({
      nowYear: e.detail.value,
      yearText: yearText
    })

    this.getHeartRateData(this.data.deviceNum, e.detail.value, 4);
  },
  // 点击tab切换
  swichNav: function(e) {
    if (this.data.curTab === e.currentTarget.dataset.current) return;
    this.setData({
      curTab: e.currentTarget.dataset.current
    })

    let myMap = new Map([
      [1, "now"],
      [2, "nowWeek"],
      [3, "nowMonth"],
      [4, "nowYear"]
    ])

    this.getHeartRateData(this.data.deviceNum, this.data[myMap.get(e.currentTarget.dataset.current)], e.currentTarget.dataset.current);
  },
  // 滑动切换tab
  bindChange: function(e) {
    this.setData({
      curTab: e.detail.current
    })
  },
  //计算平均心率
  getAvaHeartRate(dataList) {
    let avaHeartRate = 0,
      sum = 0,
      num = 0;
    dataList.forEach(item => {
      if (item != 0) num++;
      sum = sum + item * 1;
    })

    avaHeartRate = num ? Math.round(sum / num) : 0;
    return avaHeartRate;
  },
  //计算每4个小时平均心率,返回绘图数据
  getCirData(dataList) {

    let newArray = [{
      x: "4时",
      heartRate: this.getAvaHeartRate(dataList.slice(0, 4))
    }, {
      x: "8时",
      heartRate: this.getAvaHeartRate(dataList.slice(4, 8))
    }, {
      x: "12时",
      heartRate: this.getAvaHeartRate(dataList.slice(8, 12))
    }, {
      x: "16时",
      heartRate: this.getAvaHeartRate(dataList.slice(12, 16))
    }, {
      x: "20时",
      heartRate: this.getAvaHeartRate(dataList.slice(16, 20))
    }, {
      x: "24时",
      heartRate: this.getAvaHeartRate(dataList.slice(20, 24))
    }]

    return newArray;
  },
  heartRateDayHandle(data) {
    if (!data || !data.length) data = [{
      maxHeartRate: 0,
      minHeartRate: 0,
      heartRateArray: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
    }];

    let heartRate = data[0];
    let heartRateArray = heartRate.heartRateArray ? heartRate.heartRateArray.split(",") : [];
    this.setData({
      maxRateDay: this.data.maxInt.includes(heartRate.maxHeartRate) ? 0 : heartRate.maxHeartRate,
      minRateDay: this.data.maxInt.includes(heartRate.minHeartRate) ? 0 : heartRate.minHeartRate,
      avaRateDay: this.getAvaHeartRate(heartRateArray)
    })

    let dayChartComponent = this.selectComponent('#column-day');
    dayChartComponent.chart.changeData(this.getCirData(heartRateArray));

    let ava_r = this.data.avaRateDay / 180;
    ava_r = ava_r >= 1 ? 1 : ava_r;
    let max_r = this.data.maxRateDay / 180;
    max_r = max_r >= 1 ? 1 : max_r;
    let min_r = this.data.minRateDay / 180;
    min_r = min_r >= 1 ? 1 : min_r;

    this.drawCir("can-maxRate-day", max_r);
    this.drawCir("can-minRate-day", min_r);
    this.drawCir("can-avaRate-day", ava_r);
  },
  heartRateWeekHandle(data) {
    if (!data || !data.length) data = [{
      heartRatePeriodDate: new Date(this.data.nowWeek).getTime(),
      maxHeartRate: 0,
      minHeartRate: 0,
      heartRateArray: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
    }];
    let newArray = [],
      chartData = [],
      maxArr = [],
      minArr = [],
      avaArr = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = app.utils.formatWeekday(new Date(data[i].heartRatePeriodDate).getDay()).replace("星期", "周");
      maxArr.push(data[i].maxHeartRate);
      minArr.push(data[i].minHeartRate);
      newArray.push({
        weekday: weekday,
        heartRatePeriodDate: data[i].heartRatePeriodDate,
        maxHeartRate: data[i].maxHeartRate,
        minHeartRate: data[i].minHeartRate,
        heartRateArray: data[i].heartRateArray,
        heartRate: this.getAvaHeartRate(data[i].heartRateArray ? data[i].heartRateArray.split(",") : []) //平均心率
      })
    }

    this.dataRepair(newArray, this.data.nowWeek, 7).forEach(item => {
      avaArr.push(item.heartRate);
      chartData.push({
        heartRate: item.heartRate,
        x: item.weekday
      })
    })

    this.setData({
      maxRateWeek: Math.max(...maxArr),
      minRateWeek: Math.min(...minArr),
      avaRateWeek: this.getAvaHeartRate(avaArr),
    })

    let weekChartComponent = this.selectComponent('#column-week');
    weekChartComponent.chart.changeData(chartData);

    let ava_r = this.data.avaRateWeek / 180;
    ava_r = ava_r >= 1 ? 1 : ava_r;
    let max_r = this.data.maxRateWeek / 180;
    max_r = max_r >= 1 ? 1 : max_r;
    let min_r = this.data.minRateWeek / 180;
    min_r = min_r >= 1 ? 1 : min_r;

    this.drawCir("can-maxRate-week", max_r);
    this.drawCir("can-minRate-week", min_r);
    this.drawCir("can-avaRate-week", ava_r);
  },
  heartRateMonthHandle(data) {
    if (!data || !data.length) data = [{
      heartRatePeriodDate: new Date(this.data.nowMonth).getTime(),
      maxHeartRate: 0,
      minHeartRate: 0,
      heartRateArray: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
    }];
    let newArray = [],
      chartData = [],
      maxArr = [],
      minArr = [],
      avaArr = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = app.utils.formatWeekday(new Date(data[i].heartRatePeriodDate).getDay()).replace("星期", "周");
      maxArr.push(data[i].maxHeartRate);
      minArr.push(data[i].minHeartRate);
      newArray.push({
        weekday: weekday,
        heartRatePeriodDate: data[i].heartRatePeriodDate,
        maxHeartRate: data[i].maxHeartRate,
        minHeartRate: data[i].minHeartRate,
        heartRateArray: data[i].heartRateArray,
        heartRate: this.getAvaHeartRate(data[i].heartRateArray ? data[i].heartRateArray.split(",") : []) //平均心率
      })
    }

    this.dataRepair(newArray, this.data.nowMonth, 15).forEach(item => {
      avaArr.push(item.heartRate);
      chartData.push({
        heartRate: item.heartRate,
        x: item.date
      })
    })

    this.setData({
      maxRateMonth: Math.max(...maxArr),
      minRateMonth: Math.min(...minArr),
      avaRateMonth: this.getAvaHeartRate(avaArr),
    })

    let monthChartComponent = this.selectComponent('#column-month');
    monthChartComponent.chart.changeData(chartData);

    let ava_r = this.data.avaRateMonth / 180;
    ava_r = ava_r >= 1 ? 1 : ava_r;
    let max_r = this.data.maxRateMonth / 180;
    max_r = max_r >= 1 ? 1 : max_r;
    let min_r = this.data.minRateMonth / 180;
    min_r = min_r >= 1 ? 1 : min_r;

    this.drawCir("can-maxRate-month", max_r);
    this.drawCir("can-minRate-month", min_r);
    this.drawCir("can-avaRate-month", ava_r);
  },
  heartRateYearHandle(data) {
    if (!data || !data.length) data = [{
      heartRatePeriodDate: new Date(this.data.nowYear).getTime(),
      maxHeartRate: 0,
      minHeartRate: 0,
      heartRateArray: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
    }];
    let newArray = [],
      chartData = [],
      maxArr = [],
      minArr = [],
      avaArr = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = new Date(data[i].heartRatePeriodDate).format("MM");
      maxArr.push(data[i].maxHeartRate);
      minArr.push(data[i].minHeartRate);
      newArray.push({
        weekday: weekday,
        heartRatePeriodDate: data[i].heartRatePeriodDate,
        maxHeartRate: data[i].maxHeartRate,
        minHeartRate: data[i].minHeartRate,
        heartRateArray: data[i].heartRateArray,
        heartRate: this.getAvaHeartRate(data[i].heartRateArray ? data[i].heartRateArray.split(",") : []) //平均心率
      })
    }

    let dataYear = new Map([
      ["01", []],
      ["02", []],
      ["03", []],
      ["04", []],
      ["05", []],
      ["06", []],
      ["07", []],
      ["08", []],
      ["09", []],
      ["10", []],
      ["11", []],
      ["12", []]
    ])
    let startMonth;
    this.dataRepair(newArray, this.data.nowYear, 365).forEach((item, index) => {
      if (index == 0) startMonth = item.month;
      let monthData = dataYear.get(item.month);
      monthData.push(item.heartRate);
      dataYear.set(item.month, monthData);
    });

    let that = this;
    dataYear.forEach((value, key) => {
      avaArr.push(that.getAvaHeartRate(value));
      chartData.push({
        heartRate: that.getAvaHeartRate(value),
        x: key
      })
    })

    this.setData({
      maxRateYear: Math.max(...maxArr),
      minRateYear: Math.min(...minArr),
      avaRateYear: this.getAvaHeartRate(avaArr),
    })


    //按照开始月份调整数组顺序
    let index = startMonth * 1 - 1;
    let arrBegin = chartData.slice(0, index);
    let arrEnd = chartData.slice(index);
    let dataList = arrEnd.concat(arrBegin);

    let yearChartComponent = this.selectComponent('#column-year');
    yearChartComponent.chart.changeData(dataList);

    let ava_r = this.data.avaRateYear / 180;
    ava_r = ava_r >= 1 ? 1 : ava_r;
    let max_r = this.data.maxRateYear / 180;
    max_r = max_r >= 1 ? 1 : max_r;
    let min_r = this.data.minRateYear / 180;
    min_r = min_r >= 1 ? 1 : min_r;

    this.drawCir("can-maxRate-year", max_r);
    this.drawCir("can-minRate-year", min_r);
    this.drawCir("can-avaRate-year", ava_r);
  },
  //修复空白数据
  dataRepair(data, end, days) {
    let newArr = [];
    let endTime = new Date(end + " 23:59:59").getTime();
    let startTime = endTime - days * 24 * 3600 * 1000 + 1000;
    if (days == 365) {
      let year = new Date(endTime).getFullYear() - 1;
      let month = new Date(endTime).getMonth() + 2;
      month = month > 12 ? 12 : month;
      let date = year + "/" + month + "/01";
      startTime = new Date(date).getTime();
    }

    data.forEach((item, i) => {
      item.heartRatePeriodDate = new Date(new Date(item.heartRatePeriodDate).format("yyyy/MM/dd 18:00")).getTime();
    })

    data.forEach((item, i) => {
      if (i != 0) {
        let d = (item.heartRatePeriodDate - data[i - 1].heartRatePeriodDate) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d >= 1) {
          for (let j = 0; j < d - 1; j++) {
            let weekday = app.utils.formatWeekday(new Date(data[i - 1].heartRatePeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).getDay())
              .replace("星期", "周");
            let month = new Date(data[i - 1].heartRatePeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("MM");
            let date = new Date(data[i - 1].heartRatePeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("dd");
            newArr.push({
              heartRate: 0,
              weekday: weekday,
              month: month,
              date: date
            })
          }

          let month = new Date(item.heartRatePeriodDate).format("MM");
          let date = new Date(item.heartRatePeriodDate).format("dd");
          newArr.push({
            heartRate: item.heartRate,
            weekday: item.weekday,
            month: month,
            date: date
          })
        } else {
          let month = new Date(item.heartRatePeriodDate).format("MM");
          let date = new Date(item.heartRatePeriodDate).format("dd");
          newArr.push({
            heartRate: item.heartRate,
            weekday: item.weekday,
            month: month,
            date: date
          })
        }
      } else if (i == 0) {
        let d = (item.heartRatePeriodDate - startTime) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d >= 1) {
          for (let j = 0; j < d; j++) {
            let weekday = app.utils.formatWeekday(new Date(startTime + j * (24 * 60 * 60 * 1000)).getDay())
              .replace("星期", "周");
            let month = new Date(startTime + j * (24 * 60 * 60 * 1000)).format("MM");
            let date = new Date(startTime + j * (24 * 60 * 60 * 1000)).format("dd");
            newArr.push({
              heartRate: 0,
              weekday: weekday,
              month: month,
              date: date
            })
          }

          let month = new Date(item.heartRatePeriodDate).format("MM");
          let date = new Date(item.heartRatePeriodDate).format("dd");
          newArr.push({
            heartRate: item.heartRate,
            weekday: item.weekday,
            month: month,
            date: date
          })
        } else {
          let month = new Date(item.heartRatePeriodDate).format("MM");
          let date = new Date(item.heartRatePeriodDate).format("dd");
          newArr.push({
            heartRate: item.heartRate,
            weekday: item.weekday,
            month: month,
            date: date
          })
        }
      }
      //结尾不连续
      if (i == (data.length - 1)) {
        let d = (endTime - item.heartRatePeriodDate) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d > 1) {
          for (let j = 0; j < d; j++) {
            let weekday = app.utils.formatWeekday(new Date(item.heartRatePeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).getDay())
              .replace("星期", "周");
            let month = new Date(item.heartRatePeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("MM");
            let date = new Date(item.heartRatePeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("dd");
            newArr.push({
              heartRate: 0,
              weekday: weekday,
              month: month,
              date: date
            })
          }
        }
      }

    })

    return newArr;
  },
  //根据手环设备号获取心率
  getHeartRateData(deviceNum, date, type) {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getHeartRateData", {
      deviceNum: deviceNum,
      type: type,
      date: date
    }).then(response => {
      if (response.data.error == 10000) {
        if (type == 1) return that.heartRateDayHandle(response.data.data);
        if (type == 2) return that.heartRateWeekHandle(response.data.data);
        if (type == 3) return that.heartRateMonthHandle(response.data.data);
        if (type == 4) return that.heartRateYearHandle(response.data.data);
      }
    }).catch(err => {})
  }
})